<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    html {
      height: 100%;
    }

    body {
      margin: 0;
      padding: 0;
      border: 0;
      height: 100%;
    }
  </style>
</head>
<body>
<script src="/lib/vips.js?<%= __webpack_hash__ %>"></script>
<script type="module">
  /* global Vips, cleanup */

  // TODO: `dynamicModules` should be imported from './samples' instead.
  const dynamicModules = [
    {
      id: 'jxl',
      file: 'vips-jxl.wasm'
    },
    {
      id: 'heif',
      file: 'vips-heif.wasm'
    },
    {
      id: 'resvg',
      file: 'vips-resvg.wasm'
    }
  ];

  let loadedElements = [];

  window.addEventListener('message', load);

  function load (event) {
    loadedElements = loadedElements.filter(el => el.remove());
    if (typeof cleanup === 'function') {
      cleanup();
    }

    const data = event.data;

    if (data.css) {
      const style = document.createElement('style');
      style.type = 'text/css';
      style.innerHTML = data.css;
      document.head.appendChild(style);
      loadedElements.push(style);
    }
    if (data.html) {
      const content = document.createElement('div');
      content.style.height = '100%';
      content.innerHTML = data.html;
      document.body.insertBefore(content, document.body.firstChild);
      loadedElements.push(content);
    }
    if (data.js) {
      try {
        // eslint-disable-next-line no-eval
        eval('(async () => {\n' + data.js + '\n})()');
      } catch (err) {
        const pre = document.createElement('pre');
        pre.appendChild(document.createTextNode(err));
        document.body.insertBefore(pre, document.body.firstChild);
        loadedElements.push(pre);
      }
    }
  }

  const options = {
    print: (stdout) => console.log(stdout.replace(/\033\[[0-9;]*m/g, '')),
    locateFile: (fileName, scriptDirectory) => `${scriptDirectory}${fileName}?<%= __webpack_hash__ %>`,
    // Avoid using the browser's image decoder to decode preloaded files
    noImageDecoding: true,
    preRun: (module) => {
      module.setAutoDeleteLater(!document.referrer.includes('disableAutoDelete'));
      module.setDelayFunction(fn => {
        globalThis.cleanup = fn;
      });

      // Handy for debugging
      // module.ENV.VIPS_INFO = 1;
      // module.ENV.VIPS_LEAK = 1;

      // Preload playground files
      const images = [
        'owl.jpg', 'owl.tif', 'owl.webp', 'owl.jxl', 'owl.avif',
        'banana.webp', 'banana.gif',
        'alphachannel.svg', 'transparency_demo.png'
      ];
      for (const image of images) {
        module.FS.createPreloadedFile('/', image, 'assets/images/' + image, true, false);
      }
    },
    postRun: (module) => {
      const pad = 30;
      const have = (name) => module.Utils.typeFind('VipsOperation', name) !== 0;

      console.log('vips version:'.padEnd(pad), module.version());
      console.log('Emscripten version:'.padEnd(pad), module.emscriptenVersion());
      // console.log(module.config());
      console.log('Concurrency:'.padEnd(pad), module.concurrency());

      console.log('Cache max mem:'.padEnd(pad), module.Cache.maxMem());
      console.log('Cache max operations:'.padEnd(pad), module.Cache.max());
      console.log('Cache current operations:'.padEnd(pad), module.Cache.size());
      console.log('Cache max open files:'.padEnd(pad), module.Cache.maxFiles());

      console.log('Memory allocations:'.padEnd(pad), module.Stats.allocations());
      console.log('Memory currently allocated:'.padEnd(pad), module.Stats.mem());
      console.log('Memory high water:'.padEnd(pad), module.Stats.memHighwater());
      console.log('Open files:'.padEnd(pad), module.Stats.files());

      console.log('JPEG support:'.padEnd(pad), have('jpegload') ? 'yes' : 'no');
      console.log('JPEG XL support:'.padEnd(pad), have('jxlload') ? 'yes' : 'no');
      console.log('AVIF support:'.padEnd(pad), have('heifload') ? 'yes' : 'no');
      console.log('PNG support:'.padEnd(pad), have('pngload') ? 'yes' : 'no');
      console.log('TIFF support:'.padEnd(pad), have('tiffload') ? 'yes' : 'no');
      console.log('WebP support:'.padEnd(pad), have('webpload') ? 'yes' : 'no');
      console.log('GIF support:'.padEnd(pad), have('gifload') ? 'yes' : 'no');

      console.log('SVG load:'.padEnd(pad), have('svgload') ? 'yes' : 'no');

      console.log('Text rendering support:'.padEnd(pad), have('text') ? 'yes' : 'no');
    }
  };

  // Control the dynamic modules via the ?modules= query string
  const params = new URL(document.referrer).searchParams;
  if (params.has('modules')) {
    const enabledModules = params.get('modules').split('-').filter(id => id.length > 2);
    options.dynamicLibraries = dynamicModules.filter(module => enabledModules.some(id => module.id === id)).map(module => module.file);
  }

  globalThis.vips = await Vips(options);
  window.parent.postMessage('vipsInitialized', '*');
</script>
</body>
</html>
